import { InfoItem } from '/@/model/workflow/bpmnConfig';
import { useBpmnStore } from '/@bpmn/store/bpmn';
import { BpmnNodeKey, MultipleInstancesType } from '/@/enums/workflowEnum';
import { FormFiledConfig, FormFiled } from '/@/model/workflow/memberSetting';
import { TreeProps } from 'ant-design-vue';
import { getNodeName } from './property';
import { FormConfigItem } from '/@/model/workflow/formSetting';
import { getDesignInfo } from '/@/api/workflow/design';
import { doNotTypes, hiddenComponentType, visitorsBookType } from './formPermission';
import { useI18n } from '/@/hooks/web/useI18n';
const { t } = useI18n();
export const separator = '___';
/**
 * 获取意见簿树
 * @param formConfigs 表单数据配置
 * @returns []
 */
export function getOpinionConfigTree(formConfigs: Array<FormConfigItem>) {
  const children: Array<FormFiled> = [];
  if (formConfigs && formConfigs.length > 0) {
    formConfigs.forEach((ele1) => {
      const formChildren: Array<FormFiled> = [];
      if (ele1.children && ele1.children.length > 0) {
        ele1.children.forEach((ele2) => {
          if (ele2.type == visitorsBookType) {
            const key = ele1.key + separator + ele2.key;
            formChildren.push({
              title: ele2.fieldName,
              key,
              formId: ele1.formId,
              formField: ele2.key,
              disabled: false,
              children: [],
            });
          }
        });
      }
      children.push({
        title: ele1.formName,
        key: ele1.formId,
        formId: ele1.formId,
        formField: '',
        disabled: true,
        children: formChildren,
      });
    });
  }
  return children;
}
/**
 * 获取表单树
 * @param formConfigs 表单数据配置
 * @param nodeId 节点id
 * @param needHideComponents 是否需要隐藏组件
 * @returns []
 */
export function getFormSettingTree(
  formConfigs: Array<FormConfigItem>,
  nodeId = '',
  nodeName = '',
  needHideComponents = false,
  needSubTable = false,
  needMainTable = true,
) {
  const store = useBpmnStore();
  const { infoId } = store;
  nodeId = nodeId ? nodeId : infoId;
  const children: Array<FormFiled> = [];
  if (formConfigs && formConfigs.length > 0) {
    formConfigs.forEach((ele1) => {
      const formChildren: Array<FormFiled> = [];
      if (ele1.children && ele1.children.length > 0) {
        ele1.children.forEach((ele2) => {
          if (ele2.isSubTable) {
            // 子表
            if (needSubTable) {
              const tabChildren: Array<FormFiled> = [];
              const key = nodeId + separator + ele1.key + separator + ele2.fieldId;
              ele2.children.forEach((ele3) => {
                if (doNotTypes.includes(ele3.type)) {
                  // 剔除
                } else if (ele3.type === hiddenComponentType) {
                  // 隐藏组件
                } else {
                  const key =
                    nodeId +
                    separator +
                    ele1.key +
                    separator +
                    ele2.fieldId +
                    separator +
                    ele3.fieldId;
                  if (ele3.fieldId) {
                    tabChildren.push({
                      title: ele3.fieldName,
                      label:
                        nodeName +
                        '-' +
                        ele1.formName +
                        '-' +
                        ele2.fieldName +
                        '-' +
                        ele3.fieldName,
                      key,
                      formId: ele1.formId,
                      formField: ele3.fieldId,
                      disabled: false,
                      children: [],
                    });
                  }
                }
              });

              formChildren.push({
                title: ele2.fieldName,
                label: nodeName + '-' + ele1.formName + '-' + ele2.fieldName,
                key,
                formId: ele1.formId,
                formField: ele2.fieldId,
                disabled: true,
                children: tabChildren,
              });
            }
          } else {
            if (needMainTable) {
              if (doNotTypes.includes(ele2.type)) {
                // 剔除
              } else if (ele2.type === hiddenComponentType) {
                // 隐藏组件
                if (needHideComponents) {
                  const key = nodeId + separator + ele1.key + separator + ele2.fieldId;
                  formChildren.push({
                    title: ele2.fieldName,
                    label: nodeName + '-' + ele1.formName + '-' + ele2.fieldName,
                    key,
                    formId: ele1.formId,
                    formField: ele2.fieldId,
                    disabled: false,
                    children: [],
                  });
                }
              } else {
                const key = nodeId + separator + ele1.key + separator + ele2.fieldId;
                if (ele2.fieldId) {
                  formChildren.push({
                    title: ele2.fieldName,
                    label: nodeName + '-' + ele1.formName + '-' + ele2.fieldName,
                    key,
                    formId: ele1.formId,
                    formField: ele2.fieldId,
                    disabled: false,
                    children: [],
                  });
                }
              }
            }
          }
        });
      }
      children.push({
        title: ele1.formName,
        label: nodeName + '-' + ele1.formName,
        key: nodeId + separator + ele1.key,
        formId: ele1.formId,
        formField: '',
        disabled: true,
        children: formChildren,
      });
    });
  }
  return children;
}

/**
 * 获取当前流程变量数据树
 * @param parameter 参数配置
  {
   needUserNodeButton 是否需要按钮组 下面的按钮值列表[默认不需要，默认false]
    needHideComponents 是否需要隐藏组件[默认不需要，默认false]
   }
 * @returns []
 */
export function getVariablesTree(parameter?: {
  needUserNodeButton?: boolean;
  needHideComponents?: boolean;
}): TreeProps['treeData'] {
  const params = {
    ...{
      needUserNodeButton: false,
      needHideComponents: false,
      needSubTable: false,
      needMainTable: true,
    },
    ...parameter,
  };
  const treeData: TreeProps['treeData'] = [];
  const store = useBpmnStore();
  const { info, processInfo } = store;
  const temp = parsingFormConfigJsonTree(info.values(), processInfo.processId, params);
  treeData.push(...temp);
  return treeData;
}

/**
 * 获取多实例，发起人配置中，只允许子表表单配置
 */
export function getVariablesSubTableTree(): TreeProps['treeData'] {
  const params = {
    ...{
      needUserNodeButton: false,
      needHideComponents: false,
      needSubTable: true,
      needMainTable: false,
    },
  };
  const treeData: TreeProps['treeData'] = [];
  const store = useBpmnStore();
  const { info, processInfo } = store;
  const temp = parsingFormConfigJsonTree(info.values(), processInfo.processId, params);
  treeData.push(...temp);

  return treeData;
}
// 根据json，以及主要流程Id，获取节点到表单到字段的树
function parsingFormConfigJsonTree(
  info: any,
  mainProcessId: any,
  params: {
    needUserNodeButton: boolean;
    needHideComponents: boolean;
    needSubTable: boolean;
    needMainTable: boolean;
  },
) {
  const list: TreeProps['treeData'] = [];

  for (const item of info) {
    const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER, BpmnNodeKey.CALLACTIVITY];
    if (showNodeTypes.includes(item.type) && item.parentId == mainProcessId) {
      const name = item.name ? item.name : item.type;
      const id = item.id;
      const children = getFormSettingTree(
        item.formConfigs,
        id,
        name,
        params.needHideComponents,
        params.needSubTable,
        params.needMainTable,
      );

      const config: FormFiledConfig = {
        title: name,
        label: name,
        key: id,
        disabled: true,
        children,
      };
      //  按钮组
      if (item.type == BpmnNodeKey.USER && params.needUserNodeButton) {
        const variableValueList: Array<FormFiledConfig> = [];
        item.buttonConfigs.forEach((ele) => {
          if (ele.checked) {
            variableValueList.push({
              title: ele.buttonName,
              key: ele.buttonCode,
              disabled: false,
              children: [],
              buttons: [],
            });
          }
        });
        const buttonInfo = getButtonListChildren(id, name, variableValueList);
        config.children.push(buttonInfo);
      }
      //用户任务  多实例（会签） 审批结果
      if (
        item.type == BpmnNodeKey.USER &&
        item.countersignConfig.multipleInstancesType !== MultipleInstancesType.NONE
      ) {
        config.children.push({
          title: t('按钮组'),
          label: name + '-' + t('审批结果'),
          key: id + separator + 'button' + separator + 'result',
          disabled: false,
          children: [],
        });
      }

      // //外部流程 按钮组
      // if (item.type == BpmnNodeKey.CALLACTIVITY && params.needUserNodeButton) {
      //   info.children.push({
      //     title: t('按钮组'),
      //     label: name + '-' + t('完成数量'),
      //     key: id + separator + 'finish' + separator + 'count',
      //     disabled: false,
      //     children: [],
      //   });
      // }

      list.push(config);
    }
  }
  return list;
}
// 获取节点的按钮组
const getButtonListChildren = (id: string, name: string, variableValueList) => {
  const buttons: Array<{
    title: string;
    key: string;
    disabled: boolean;
    children: [];
  }> = [];
  // const key = id + separator + 'button';
  variableValueList.forEach((element) => {
    buttons.push({
      title: element.title,
      key: element.key,
      disabled: false,
      children: [],
    });
  });
  return {
    title: t('按钮组'),
    label: name + '-' + t('按钮组'),
    key: id + separator + 'button',
    disabled: false,
    children: [],
    buttons,
  };
};

// 获取所有节点列表数据 【只包含开始节点以及用户节点】
export function getNodeList() {
  const list: Array<InfoItem> = [];
  const store = useBpmnStore();
  const { info } = store;
  for (const item of info.values()) {
    const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER];
    if (showNodeTypes.includes(item.type)) {
      const name = item.name ? item.name : getNodeName(item.type);
      list.push({ ...item, name });
    }
  }
  return list;
}
// 获取主流程的节点数据 【只包含开始节点以及用户节点】
export function getMainProcessNodeList() {
  const list: Array<{ id: string; name: string }> = [];
  const store = useBpmnStore();
  const { info, processInfo } = store;
  const mainProcessId = processInfo.processId;
  for (const item of info.values()) {
    const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER];
    if (showNodeTypes.includes(item.type) && item.parentId == mainProcessId) {
      const name = item.name ? item.name : getNodeName(item.type);
      list.push({ id: item.id, name });
    }
  }
  return list;
}
// 获取流程参数
export function getProcessParamConfigs() {
  const bpmnStore = useBpmnStore();
  return bpmnStore.processInfo.processParamConfigs;
}
//获取流程参数树
function getProcessParameterTree(processParameter) {
  const treeList: TreeProps['treeData'] = [
    {
      title: t('流程参数'),
      key: 'processParameter',
      disabled: true,
      children: [],
    },
  ];
  processParameter.forEach((ele) => {
    if (treeList && treeList[0] && treeList[0].children)
      treeList[0].children.push({
        title: ele.name,
        key: ele.id,
        disabled: false,
        children: [],
      });
  });
  return treeList;
}
//获取流程Json配置树【显示流程参数，以及所有节点表单配置】
function parsingJson(
  info: any,
  processInfo: any,
  parameter?: {
    needUserNodeButton?: boolean;
    needHideComponents?: boolean;
    needSubTable?: boolean;
  },
) {
  const params = {
    ...{
      needUserNodeButton: false,
      needHideComponents: false,
      needSubTable: false,
      needMainTable: true,
    },
    ...parameter,
  };
  const processParamConfigs = getProcessParamConfigs();
  const list: TreeProps['treeData'] = getProcessParameterTree(processParamConfigs);
  const temp: TreeProps['treeData'] = parsingFormConfigJsonTree(
    info,
    processInfo.processId,
    params,
  );
  list.push(...temp);

  return list;
}

// 外部流程-来源树
export function getSourceList() {
  const store = useBpmnStore();
  const { info, processInfo } = store;
  return parsingJson(info.values(), processInfo);
}
// 外部流程-变量来源 主流程树 单实例

export function getSingleMainSourceList() {
  const store = useBpmnStore();
  const { info, processInfo } = store;
  return parsingJson(info.values(), processInfo, {
    needUserNodeButton: false,
    needHideComponents: true,
    needSubTable: false,
  });
}
// 外部流程-变量来源 主流程树 多实例

export function getMultipleMainSourceList() {
  const store = useBpmnStore();
  const { info, processInfo } = store;
  return parsingJson(info.values(), processInfo, {
    needUserNodeButton: false,
    needHideComponents: true,
    needSubTable: true,
  });
}

// 外部流程-目标树
export async function getTargetList(id: string) {
  const res = await getDesignInfo(id);
  const json = JSON.parse(res?.jsonContent);
  return parsingJson(json.childNodeConfig, json.processConfig);
}
/**
 * 获取Json，xml
 * @param id 流程模板id
 * @returns {json,xml}
 */
export async function getBpmnJsonAndXmlById(id: string) {
  const res = await getDesignInfo(id);
  const json = JSON.parse(res?.jsonContent);
  const xml = res?.xmlContent;
  return { json, xml };
}

// 获取所有节点表单使用列表
export function getUsedFormList() {
  const formKeyList = {};
  const formList = {};
  const store = useBpmnStore();
  const { info, infoId, getProperties } = store;
  let disabledIds: Array<string> = [];
  const val = getProperties(infoId);
  if (val && val.formConfigs && val.formConfigs.length > 0) {
    disabledIds = val.formConfigs.map((ele) => {
      return ele.formId;
    });
  }
  for (const item of info.values()) {
    const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER];
    if (showNodeTypes.includes(item.type)) {
      if (item.formConfigs.length > 0) {
        item.formConfigs.forEach((element) => {
          if (formKeyList[element.key]) {
            if (formKeyList[element.key]['nodeIds']) {
              formKeyList[element.key]['nodeIds'].push(item.id);
            }
          } else {
            formKeyList[element.key] = element;
            formKeyList[element.key]['nodeIds'] = [item.id];
          }
          if (formList[element.formId]) {
            if (formList[element.formId] && !disabledIds.includes(element.formId)) {
              formList[element.formId].push(element.key);
            }
          } else {
            if (!disabledIds.includes(element.formId)) formList[element.formId] = [element.key];
          }
        });
      }
    }
  }
  const notRepeatedList: Array<any> = [];
  const repeatedList = {};
  for (const [key, value] of Object.entries(formList)) {
    if (value && Array.isArray(value)) {
      const setForms = [...new Set(value)];
      if (setForms.length == 1) {
        notRepeatedList.push(setForms[0]);
      } else {
        repeatedList[key] = setForms;
      }
    }
  }
  return {
    formKeyList,
    repeatedList,
    notRepeatedList,
  };
}

// 获取所有节点表单使用列表
export function getUsedFormIds() {
  const usedFormIds: Array<string> = [];
  const store = useBpmnStore();
  const { info } = store;
  for (const item of info.values()) {
    const showNodeTypes = [BpmnNodeKey.START, BpmnNodeKey.USER];
    if (showNodeTypes.includes(item.type)) {
      if (item.formConfigs.length > 0) {
        item.formConfigs.forEach((element) => {
          if (element.formId) {
            usedFormIds.push(element.formId);
          }
        });
      }
    }
  }
  return [...new Set(usedFormIds)];
}
